package network;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpEchoServer {
    private DatagramSocket socket = null;
    //    通过构造方法来实例化
    public UdpEchoServer(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动");
        while (true){
//            1.读取请求并解析                      UDP数据报
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096],4096);
//            如果客户端没有发送请求，服务器代码会在receive这里阻塞
            socket.receive(requestPacket);
//            为了方便在java代码中处理，可以将上述数据包中的二进制数据拿出来构成String
            String request = new String(requestPacket.getData(),0,requestPacket.getLength());
//            2.根据请求计算响应
            String response = process(request);
//            3.把响应写回客户端
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),0,response.getBytes().length,
                    requestPacket.getSocketAddress());
//                                需要知道传给谁（端口号）
            socket.send(responsePacket);
            System.out.printf("[%s:%d] req=%s,resp=%s\n",requestPacket.getAddress(),requestPacket.getPort(),request,response);
        }
    }

//    回显服务器
//    private String process(String request) {
//        return request;
//    }
    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
//        程序一启动就会通过构造方法，实例化对象
        UdpEchoServer server = new UdpEchoServer(9090);
        server.start();
    }
}
